// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    cartItems: [],
    selectedProduct: null,
  },
  mutations: {
    ADD_TO_CART(state, product) {
      let found = state.cartItems.find(item => item.goodsId === product.goodsId);
      if (!found) {
        state.cartItems.push({ ...product, quantity: 1 });
      } else {
        found.quantity += 1;
      }
    },
    UPDATE_QUANTITY(state, { goodsId, quantity }) {
      let item = state.cartItems.find(item => item.goodsId === goodsId);
      if (item) {
        item.quantity = quantity;
      }
    },
    CLEAR_CART(state) {
      state.cartItems = [];
    },
    setSelectedProduct(state, product) {
      state.selectedProduct = product;
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('ADD_TO_CART', product);
    },
    updateQuantity({ commit }, { goodsId, quantity }) {
      commit('UPDATE_QUANTITY', { goodsId, quantity });
    },
    clearCart({ commit }) {
      commit('CLEAR_CART');
    },
    selectProduct({ commit }, product) {
      commit('setSelectedProduct', product);
    }
  },
  getters: {
    selectedProduct: state => state.selectedProduct
  }
});

export default store;